package com.example.satokendemo01.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.util.SaResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

@ControllerAdvice
public class GlobalExceptionHandler {
	private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	//登录异常
	@ExceptionHandler(NotLoginException.class)
	@ResponseStatus(HttpStatus.OK)	// HttpStatus.OK是因为前端不基于httpStatus去判断接口是否异常
	@ResponseBody
	public SaResult handleNoHandlerFoundException(NotLoginException e) {
		log.error("用户未登录 ", e);
		// ErrorCode.LOGIN_REQUIRE.getCode() 是未登录时的与前端约定好的异常编码
		return SaResult.error(e.getMessage()).setCode(401);
	}

	//404异常
	@ExceptionHandler(NoHandlerFoundException.class)
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public SaResult handle404Error(NoHandlerFoundException e) {
		log.error("访问资源不存在", e);
		return new SaResult(404, "访问的资源不存在", null);
	}

	//其他异常
	@ExceptionHandler(SaTokenException.class)
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public SaResult handleSaTokenException(SaTokenException e) {
		log.error("sa-token抛出其他异常 ", e);
		return SaResult.error(e.getMessage());
	}
}
